const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    totalPages: 0,
    modelIndex: 0,
    processIndex: 0,
    modelOptions: [{ id: '', name: '全部型号' }],
    processOptions: [{ id: '', name: '全部工序' }],
    loading: false,
    // 权限相关数据
    hasViewPermission: false,
    hasAddPermission: false,
    hasEditPermission: false,
    hasDeletePermission: false,
    hasBatchPermission: false
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/process-prices/process-prices')) {
      return
    }
    
    this.checkPermissions()
    
    this.loadModels()
    this.loadProcesses()
    this.loadData()
  },

  onShow() {
    this.loadData()
  },

  onPullDownRefresh() {
    this.setData({
      page: 1
    })
    this.loadData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.page < this.data.totalPages) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData(true)
    }
  },

  async loadModels() {


      try {
        const res = await api.getProductModelList({
          status: 1
        })

      if (res.code === 1) {
        const models = res.data.list.map(item => ({
          id: item.id,
          name: `${item.product ? item.product.name : ''} - ${item.name}`
        }))
        
        this.setData({
          modelOptions: [{ id: '', name: '全部型号' }, ...models]
        })
      }
    } catch (error) {
      console.error('加载型号列表失败:', error)
    }
  },

  async loadProcesses() {
    try {
      const res = await api.getProcessList({
        status: 1
      })

      if (res.code === 1) {
        const processes = res.data.list.map(item => ({
          id: item.id,
          name: item.name
        }))
        
        this.setData({
          processOptions: [{ id: '', name: '全部工序' }, ...processes]
        })
      }
    } catch (error) {
      console.error('加载工序列表失败:', error)
    }
  },

  async loadData(append = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        page: this.data.page,
        limit: this.data.limit
      }

      if (this.data.modelIndex > 0) {
        params.model_id = this.data.modelOptions[this.data.modelIndex].id
      }

      if (this.data.processIndex > 0) {
        params.process_id = this.data.processOptions[this.data.processIndex].id
      }


      const res = await api.getProcessPriceList(params)

      if (res.code === 1) {
        const list = res.data.list.map(item => ({
          ...item,
          createtime_text: this.formatTime(item.createtime)
        }))

        this.setData({
          list: append ? [...this.data.list, ...list] : list,
          total: res.data.total,
          totalPages: Math.ceil(res.data.total / this.data.limit)
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载工价列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  onModelChange(e) {
    this.setData({
      modelIndex: parseInt(e.detail.value),
      page: 1
    })
    this.loadData()
  },

  onProcessChange(e) {
    this.setData({
      processIndex: parseInt(e.detail.value),
      page: 1
    })
    this.loadData()
  },

  onAdd() {
    wx.navigateTo({
      url: '/pages/process-price-detail/process-price-detail'
    })
  },

  onBatch() {
    wx.navigateTo({
      url: '/pages/process-price-batch/process-price-batch'
    })
  },

  onEdit(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/process-price-detail/process-price-detail?id=${item.id}`
    })
  },

  onDelete(e) {
    const item = e.currentTarget.dataset.item
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除该工价设置吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await api.deleteProcessPrice(item.id)

            if (result.code === 1) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadData()
            } else {
              wx.showToast({
                title: result.msg || '删除失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('删除工价失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  onItemClick(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/process-price-detail/process-price-detail?id=${item.id}`
    })
  },

  onPrevPage() {
    if (this.data.page > 1) {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData()
    }
  },

  onNextPage() {
    if (this.data.page < this.data.totalPages) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData()
    }
  },

  formatTime(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  },

  // 检查权限
  checkPermissions() {
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    
    if (!adminInfo || !adminInfo.id) {
      this.setData({
        hasViewPermission: false,
        hasAddPermission: false,
        hasEditPermission: false,
        hasDeletePermission: false,
        hasBatchPermission: false
      });
      return;
    }
    
    // 超级管理员拥有所有权限
    if (adminInfo.id == 1 || adminInfo.id === 1 || adminInfo.id === '1') {
      this.setData({
        hasViewPermission: true,
        hasAddPermission: true,
        hasEditPermission: true,
        hasDeletePermission: true,
        hasBatchPermission: true
      });
      return;
    }
    
    // 检查各项权限
    const hasViewPermission = permissionUtils.hasPermission(adminInfo.id, 'price_manage', 'view');
    const hasAddPermission = permissionUtils.hasPermission(adminInfo.id, 'price_manage', 'add');
    const hasEditPermission = permissionUtils.hasPermission(adminInfo.id, 'price_manage', 'edit');
    const hasDeletePermission = permissionUtils.hasPermission(adminInfo.id, 'price_manage', 'delete');
    const hasBatchPermission = permissionUtils.hasPermission(adminInfo.id, 'price_manage', 'batch');
    
    this.setData({
      hasViewPermission,
      hasAddPermission,
      hasEditPermission,
      hasDeletePermission,
      hasBatchPermission
    });
    
    // 如果没有查看权限，显示提示并返回
    if (!hasViewPermission) {
      wx.showToast({
        title: '无权限访问此页面',
        icon: 'none',
        duration: 2000
      });
      
      setTimeout(() => {
        this.goBack();
      }, 2000);
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1,
      fail: () => {
        wx.switchTab({
          url: '/pages/index/index'
        });
      }
    });
  }
})
